package com.bdqn.controller.dev;

import com.alibaba.fastjson.JSON;
import com.bdqn.constant.Constants;
import com.bdqn.constant.PageSupport;
import com.bdqn.pojo.*;
import com.bdqn.service.common.AppCategoryService;
import com.bdqn.service.common.AppInfoService;
import com.bdqn.service.common.AppVersionService;
import com.bdqn.service.common.DataDictionaryService;
import com.bdqn.service.dev.DevUserService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/**/dev")
public class DevUserController {
    private Logger logger = Logger.getLogger(DevUserController.class);
    @Resource
    private DevUserService devUserService;
    @Resource
    private DataDictionaryService dataDictionaryService;
    @Resource
    private AppCategoryService appCategoryService;
    @Resource
    private AppInfoService appInfoService;
    @Resource
    private AppVersionService appVersionService;

    @RequestMapping("/login")
    public String toLogin() {
        logger.info("进入开发者登录");
        return "/devlogin";
    }

    @PostMapping("/doLogin")
    public String doLogin(HttpSession session,
                          @RequestParam("devCode") String devCode,
                          @RequestParam("devPassword") String devPassword) {
        logger.info("进入登录界面，进行登录");
        logger.info("登录账号：" + devCode + "\t登录密码：" + devPassword);
        //获得登录对象
        DevUser devUser = devUserService.doLogin(devCode, devPassword);
        if (devUser != null) {
            //设置到session
            session.setAttribute(Constants.devUserSession, devUser);
            return "developer/main";
        }
        return "/devlogin";
    }

    @GetMapping("/app/list")
    public String list(Model model,
                       @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                       @RequestParam(value = "querySoftwareName", required = false) String softwareName,
                       @RequestParam(value = "queryStatus", required = false) Long status,
                       @RequestParam(value = "queryFlatformId", required = false) Long flatformId,
                       @RequestParam(value = "queryCategoryLevel1", required = false) Long categoryLevel1,
                       @RequestParam(value = "queryCategoryLevel2", required = false) Long categoryLevel2,
                       @RequestParam(value = "queryCategoryLevel3", required = false) Long categoryLevel3) {
        logger.info("进入查询列表方法");
        List<DataDictionary> statusList = dataDictionaryService.statusList();
        logger.info("手游状态：" + statusList + "\n");
        List<DataDictionary> flatFormList = dataDictionaryService.flatFormList();
        logger.info("所属平台：" + flatFormList + "\n");
        model.addAttribute("statusList", statusList);
        model.addAttribute("flatFormList", flatFormList);
        List<AppCategory> categoryLevel1List = appCategoryService.categoryLevel1List(null);
        logger.info("一级分类：" + categoryLevel1List + "\n");
        model.addAttribute("categoryLevel1List", categoryLevel1List);
        List<AppInfo> appInfoList = new ArrayList<>();
        //创建一个Page对象
        PageSupport pages = new PageSupport();
        try {
            //设置页面容量
            Integer pageSize = Constants.pageSize;
            pages.setPageSize(pageSize);
            logger.info("页面容量：" + pageSize);
            //获取当前页码
            pages.setCurrentPageNo(pageIndex);
            logger.info("当前页码：" + pageIndex);
            //获取当前总数据,（并获取总页数）
            pages.setTotalCount(appInfoService.pageCount(softwareName, status, flatformId, categoryLevel1,
                    categoryLevel2, categoryLevel3, pageIndex, pageSize));

            logger.info("总数据：" + pages.getTotalCount() + "\n总页码：" + pages.getTotalPageCount());
            //控制首页和尾页
            if (pageIndex > pages.getTotalPageCount()) {
                pageIndex = pages.getTotalPageCount();
                throw new RuntimeException("页码不正确");
            }
            appInfoList = appInfoService.appInfoList(softwareName, status, flatformId, categoryLevel1,
                    categoryLevel2, categoryLevel3, pageIndex, pageSize);
        } catch (Exception e) {
            logger.info(e);
        }
        model.addAttribute("pages", pages);
        model.addAttribute("appInfoList", appInfoList);
        model.addAttribute("querySoftwareName", softwareName);
        model.addAttribute("queryStatus", status);
        model.addAttribute("queryFlatformId", flatformId);
        model.addAttribute("queryCategoryLevel1", categoryLevel1);
        model.addAttribute("queryCategoryLevel2", categoryLevel2);
        model.addAttribute("queryCategoryLevel3", categoryLevel3);
        return "developer/appinfolist";
    }

    @ResponseBody
    @GetMapping("/app/categorylevellist.json")
    public Object categorylevellist(@RequestParam(value = "pid", required = false) Long pid) {
        List<AppCategory> categoryLevel2List = appCategoryService.categoryLevel1List(pid);
        logger.info("分类ID：" + pid + "\n");
        return JSON.toJSONString(categoryLevel2List);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping("/logout")
    public String logOut() {
        logger.info("退出登录");
        return "/devlogin";
    }

    @RequestMapping("/app/appinfoadd")
    public String addInfoAdd() {
        return "/developer/appinfoadd";
    }

    @ResponseBody
    @GetMapping("/app/datadictionarylist.json")
    public Object flatformAdd(@RequestParam("tcode") String typeCode) {
        logger.info("进入添加所属平台方法");
        logger.info("类型编码：" + typeCode);
        List<DataDictionary> flatformList = dataDictionaryService.flatformListAdd(typeCode);
        return JSON.toJSONString(flatformList);
    }

    /**
     * ajax后台验证--APKName是否已存在
     *
     * @param APKName
     * @return
     */
    @ResponseBody
    @GetMapping("/app/apkexist.json")
    public Object askExist(@RequestParam(value = "APKName", required = false) String APKName) {
        logger.info("进入后台验证APKName是否为空方法");
        logger.info("APKName：" + APKName);
        //创建HashMap
        HashMap<String, Object> resultMap = new HashMap<>();
        if (APKName == null || APKName.equals("")) {
            resultMap.put("APKName", "empty");
        } else {
            if (appInfoService.APKNameExist(APKName)) {
                resultMap.put("APKName", "exist");
            } else {
                resultMap.put("APKName", "noexist");
            }
        }
        return JSON.toJSONString(resultMap);
    }

    @PostMapping("/app/appinfoaddsave")
    public String addInfo(HttpServletRequest request,
                          HttpSession session,
                          AppInfo appInfo,
                          @RequestParam("a_logoPicPath") MultipartFile logoPicPath) {
        String logo = null;
        //判断文件是否为空
        if (!logoPicPath.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
            logger.info("上传文件路径：" + path);
            String originalFile = logoPicPath.getOriginalFilename();//原文件名
            logger.info("原文件名：" + originalFile);
            String prefix = FilenameUtils.getExtension(originalFile);//原文件后缀
            logger.info("原文件后缀为：" + prefix);
            int filesize = 5000000;
            logger.info("文件大小：" + logoPicPath.getSize());
            if (logoPicPath.getSize() > filesize) {//上传大小不超过5mb
                request.setAttribute("uploadFileError", "* 上传大小不得超过5mb");
                return "/developer/appinfoadd";
            } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {
                String fileName = System.currentTimeMillis() + RandomUtils.nextInt(0, 1000000) + "_Personal." + prefix;
                logger.info("新生成的文件名称为：" + fileName);
                File targetFile = new File(path);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                //保存
                try {
                    logoPicPath.transferTo(new File(targetFile, fileName));
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
                logo = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
            } else {
                return "/developer/appinfoadd";
            }
        }
        appInfo.setCreatedBy(((DevUser) session.getAttribute(Constants.devUserSession)).getId());
        appInfo.setCreationDate(new Date());
        logger.info("添加的信息：" + appInfo.toString());
        if (appInfo != null) {
            if (appInfoService.addAppInfo(appInfo)) {
                return "redirect:/dev/app/list";
            }
        }
        return "/developer/appinfoadd";
    }


    @GetMapping("/app/appinfomodify")
    public String appInfoModifySave(Model model, @RequestParam("id") Long id) {
        logger.info("进入修改页面");
        logger.info("AppInfo的ID：" + id);
        AppInfo appInfo = appInfoService.getApp(id);
        model.addAttribute("appInfo", appInfo);
        return "/developer/appinfomodify";
    }

    @PostMapping("/app/appinfomodifysave")
    public String appInfoModifySave(AppInfo appInfo, HttpSession session) {
        logger.info("进入修改页面");
        appInfo.setModifyBy(((DevUser) session.getAttribute(Constants.devUserSession)).getId());
        appInfo.setModifyDate(new Date());
        logger.info("修改后的手游信息：" + appInfo.toString());
        if (appInfoService.updateAppInfo(appInfo)) {
            return "redirect:/dev/app/list";
        }
        return "/developer/appinfomodify";
    }

    @RequestMapping("/app/appversionadd")
    public String appVersionAdd(Model model, @RequestParam("id") Long appId) {
        logger.info("进入版本添加页面");
        logger.info("获取的手游信息ID：" + appId);
        List<AppVersion> appVersionList = appVersionService.getAppVersionList(appId);
        for (AppVersion appVersion : appVersionList) {
            logger.info("版本信息：" + appVersion);
        }
        model.addAttribute("appVersionList", appVersionList);
        model.addAttribute("appId", appId);
        return "/developer/appversionadd";
    }

    @PostMapping("/app/addversionsave")
    public String addVersionSave(AppVersion appVersion, HttpSession session,
                                 HttpServletRequest request,
                                 @RequestParam(value = "a_downloadLink", required = false) MultipartFile attach) {
        logger.info("版本信息：" + appVersion.toString());
        String downloadLink = null;
        String apkLocPath = null;
        String apkFileName = null;
        if (!attach.isEmpty()) {
            String path = request.getSession().getServletContext().
                    getRealPath("statics" + File.separator + "uploadfiles");
            logger.info("uploadFile path:" + path);
            String oldFileName = attach.getOriginalFilename();//原文件名
            String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
            if (prefix.equalsIgnoreCase("apk")) {//apk文件命名：apk名称+版本号+.apk
                String apkName = null;
                try {
                    apkName = appInfoService.getApp(appVersion.getAppId()).getApkName();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (apkName == null || "".equals(apkName)) {
                    return "redirect:/dev/app/appversionadd?id="
                            + appVersion.getAppId() + "&error=error1";
                }
                apkFileName = apkName + "-" + appVersion.getVersionNo() + ".apk";
                File targetFile = new File(path, apkFileName);
                if (!targetFile.equals("a")) {
                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    return "redirect:/dev/app/appversionadd?id="
                            + appVersion.getAppId();
                }
                downloadLink = request.getContextPath() + "/statics/uploadfiles/" + apkFileName;
                apkLocPath = path + File.separator + apkFileName;
            } else {
                logger.info("attach：" + attach);

                return "redirect:/dev/app/appversionadd?id="
                        + appVersion.getAppId();
            }
            //比较版本号
//            List<AppVersion> appVersionList = appVersionService.getAppVersionList(appVersion.getAppId());
//            for (AppVersion appVersion1 : appVersionList){
//
//            }
            appVersion.setApkFileName(apkFileName);
            appVersion.setApkLocPath(apkLocPath);
            appVersion.setCreatedBy(((DevUser) session.getAttribute(Constants.devUserSession)).getId());
            appVersion.setCreationDate(new Date());
            appVersion.setDownloadLink(downloadLink);
            logger.info("版本信息：" + appVersion);
            if (appVersionService.addVersion(appVersion)) {
                logger.info("添加版本信息成功");
                Long vid = appVersionService.getMaxId();
                logger.info("最新版本的ID：" + vid);
                if (appInfoService.updateAppVersionNo(appVersion.getAppId(), vid)) {
                    logger.info("更新版本信息成功");
                    return "redirect:/dev/app/list";
                }
            }
        }
        return "/developer/appversionadd";
    }

    @RequestMapping("/app/appversionmodify")
    public String appVersionModify(Model model, @RequestParam("vid") Long vid, @RequestParam("aid") Long aid) {
        logger.info("进入修改版本页面");
        logger.info("获取的版本Id：" + vid);
        AppVersion appVersion = appVersionService.getVersionById(vid);
        logger.info("版本信息：" + appVersion);
        logger.info("获取的手游Id：" + aid);
        List<AppVersion> appVersionList = appVersionService.getAppVersionList(aid);
        model.addAttribute("appVersionList", appVersionList);
        model.addAttribute("appVersion", appVersion);
        return "/developer/appversionmodify";
    }

    @PostMapping("/app/appversionmodifysave")
    public String appVersionModifySave(AppVersion appVersion, HttpSession session,
                                       HttpServletRequest request,
                                       @RequestParam(value = "attach", required = false) MultipartFile attach) {
        logger.info("进入版本修改状态");
        logger.info("版本信息：" + appVersion);
        String downloadLink = null;
        String apkLocPath = null;
        String apkFileName = null;
        if (!attach.isEmpty()) {
            String path = request.getSession().getServletContext().
                    getRealPath("statics" + File.separator + "uploadfiles");
            logger.info("uploadFile path:" + path);
            String oldFileName = attach.getOriginalFilename();//原文件名
            String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
            if (prefix.equalsIgnoreCase("apk")) {//apk文件命名：apk名称+版本号+.apk
                String apkName = null;
                try {
                    apkName = appInfoService.getApp(appVersion.getAppId()).getApkName();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (apkName == null || "".equals(apkName)) {
                    return "redirect:/dev/app/appversionadd?id="
                            + appVersion.getAppId() + "&error=error1";
                }
                apkFileName = apkName + "-" + appVersion.getVersionNo() + ".apk";
                File targetFile = new File(path, apkFileName);
                if (!targetFile.equals("a")) {
                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    return "redirect:/dev/app/appversionadd?id="
                            + appVersion.getAppId();
                }
                downloadLink = request.getContextPath() + "/statics/uploadfiles/" + apkFileName;
                apkLocPath = path + File.separator + apkFileName;
            } else {
                logger.info("attach：" + attach);

                return "redirect:/dev/app/appversionadd?id="
                        + appVersion.getAppId();
            }
        }
        appVersion.setApkFileName(apkFileName);
        appVersion.setApkLocPath(apkLocPath);
        appVersion.setDownloadLink(downloadLink);
        appVersion.setModifyBy(((DevUser) session.getAttribute(Constants.devUserSession)).getId());
        appVersion.setModifyDate(new Date());
        logger.info("获取到的版本：" + appVersion.toString());
        if (appVersionService.updateVersion(appVersion)) {
            logger.info("成功修改版本");
            return "redirect:/dev/app/list";
        }
        return "/developer/appversionmodify";
    }

    /**
     * 删除文件
     *
     * @param id
     * @param flag
     * @return
     */
    @ResponseBody
    @RequestMapping("/app/delfile.json")
    public Object delFile(@RequestParam("id") Long id, @RequestParam("flag") String flag) {
        logger.info("进入删除图片或者apk文件方法");
        logger.info("获取的字符串flag：" + flag);
        HashMap<String, Object> map = new HashMap<>();
        if (flag.equals("apk")) {
            logger.info("进入删除和下载的方法");
            logger.info("获取的版本ID：" + id);
            if (appVersionService.delFile(id)) {
                map.put("result", "success");
            } else {
                map.put("result", "failed");
            }
        } else if (flag.equals("logo")) {
            logger.info("进入图片删除方法");
            if (appInfoService.delLogo(id)) {
                logger.info("图片删除成功");
                map.put("result", "success");
            } else {
                logger.info("图片删除失败");
                map.put("result", "failed");
            }
        }
        return JSON.toJSONString(map);
    }

    @RequestMapping("/app/appview/{appInfoId}")
    public String appView(Model model, @PathVariable("appInfoId") Long appInfoId) {
        logger.info("进入查看界面");
        logger.info("获取到的aId:" + appInfoId);
        AppInfo appInfo = appInfoService.getApp(appInfoId);
        model.addAttribute("appInfo", appInfo);
        List<AppVersion> appVersionList = appVersionService.getAppVersionList(appInfoId);
        model.addAttribute("appVersionList", appVersionList);
        return "/developer/appinfoview";
    }

    @ResponseBody
    @PutMapping("/app/delapp.json")
    public Object delApp(@RequestParam("id") Long id) {
        logger.info("进入删除方法");
        logger.info("获取到的手游ID：" + id);
        HashMap<String, Object> resultMap = new HashMap<>();
        //先判断该手游下的版本是否有记录
        int count = appVersionService.checkByAppIdCount(id);
        if (count > 0) {
            logger.info("有版本记录，记录数Count：" + count);
            if (appVersionService.delByAppId(id)) {//删除版本列表的信息
                logger.info("成功删除版本");
                if (appInfoService.del(id)) {//删除手游信息
                    logger.info("成功删除手游信息");
                    resultMap.put("delResult", "true");
                } else {
                    resultMap.put("delResult", "false");
                }
            } else {
                resultMap.put("delResult", "false");
            }
        } else {
            logger.info("没有版本记录");
            if (appInfoService.del(id)) {
                logger.info("成功删除手游信息");
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }
        return JSON.toJSONString(resultMap);
    }

    @ResponseBody
    @PostMapping("app/sale.json/{appId}")
    public Object sale(@PathVariable("appId") Long appId) {
        logger.info("进入修改上架下架方法");
        logger.info("获取手游id：" + appId);
        AppInfo appInfo = appInfoService.getApp(appId);
        logger.info("手游信息：" + appInfo);
        Date offSaleDate = null;
        Date onSaleDate = null;
        SimpleDateFormat formats = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String off = null;
        String on = null;
        HashMap<String, Object> resultMap = new HashMap<>();
        try {
            if (appInfo.getStatus() == 2 || appInfo.getStatus() == 5) {
                onSaleDate = new Date();
                on = formats.format(onSaleDate);
                appInfo.setStatus(4L);
                logger.info("手游状态：" + appInfo.getStatus());
                logger.info("上架时间：" + onSaleDate);
                resultMap.put("errorCode", '0');
            } else if (appInfo.getStatus() == 4) {
                offSaleDate = new Date();
                off = formats.format(offSaleDate);
                appInfo.setStatus(5L);
                logger.info("手游状态：" + appInfo.getStatus());
                logger.info("下架时间：" + offSaleDate);
                resultMap.put("errorCode", '0');
            }

        } catch (NullPointerException ea) {
            resultMap.put("errorCode", "param000001");
        } catch (Exception e) {
            resultMap.put("errorCode", "exception000001");
        }
        if (appInfoService.updateSale(on, off, appId, appInfo.getStatus())) {
            logger.info("修改上架下架成功");
            resultMap.put("resultMsg", "success");
        } else {
            resultMap.put("resultMsg", "failed");
        }
        return JSON.toJSONString(resultMap);
    }
}
